package com.qumitech.visualnovel.controller.rest.account;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import com.qumitech.visualnovel.model.common.BaseResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@Api(value = "账户模块", description = "账户登录相关api")
public class LoginRest {

    @ApiIgnore
    @RequestMapping("/index")
    public String index(){
        return"index";
    }

    @ApiIgnore
    @RequestMapping("/api/anonymous")
    public BaseResponse anonymous() {
        return new BaseResponse(10001, "用户未登录");
    }

    @ApiIgnore
    @RequestMapping("/403")
    public BaseResponse unauthorizedRole(){
        return new BaseResponse(-1, "没有此权限");
    }

    @ApiIgnore
    @RequestMapping("/api/logout")
    public String userLogout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "logout";
    }

    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/api/login")
    public BaseResponse login(@RequestBody JSONObject logininfo) throws Exception {
        try {
            String username = logininfo.getString("username");
            String password = logininfo.getString("password");
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            JSONObject data = new JSONObject();
            data.put("token", subject.getSession().getId());
            return new BaseResponse(0, "登录成功", data);
        } catch (IncorrectCredentialsException e) {
            return new BaseResponse(-1, "密码错误");
        } catch (LockedAccountException e) {
            return new BaseResponse(-1, "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            return new BaseResponse(-1, "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse(-1, "未知错误");
        }
    }
}
